#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2024/1/26 13:36
# @Author : Nabby
# @FileName: application.py.py

import os

from flask import Flask, request

from flask_moment import Moment
from flask_sqlalchemy import SQLAlchemy
from config import config
from flask_login import LoginManager
import flask_excel as excel
from flask_cors import CORS


from flask import json
from datetime import datetime, date

JSONEncoder = json.JSONEncoder


class CustomJSONEncoder(JSONEncoder):
    def default(self, obj):
        if isinstance(obj, datetime):
            return obj.strftime('%Y-%m-%d %H:%M:%S')
        elif isinstance(obj, date):
            return obj.strftime('%Y-%m-%d')
        else:
            return JSONEncoder.default(self, obj)

loginmanager = LoginManager()
loginmanager.session_protection = 'strong'
#loginmanager.login_view = 'base.login'

moment = Moment()
db = SQLAlchemy()
request = request

# 应用工厂函数
def create_app(config_name):
    app = Flask(__name__)
    # CORS(app)
    cors = CORS(app, resource={r"/*": {"origins": "http://47.239.253.97:80"}}, supports_credentials=True)
    #  替换默认的json编码器
    app.json_encoder = CustomJSONEncoder
    app.config.from_object(config[config_name])
    config[config_name].init_app(app)

    moment.init_app(app)
    db.init_app(app)
    loginmanager.init_app(app)


    excel.init_excel(app)
    return app

app = create_app(os.getenv('FLASK_CONFIG') or 'default')
# app = create_app(os.getenv('FLASK_CONFIG') or 'production')

# 接口注册
'''业务应用接口'''
from presentation import business_api
'''应用管理接口'''
from presentation import application_api
'''用户管理接口'''
from presentation import user_api
'''角色管理接口'''
from presentation import role_api
'''字典管理接口'''
from presentation import dict_api
